package com.c6906.vdam.das.runner;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.c6906.vdam.das.config.Rocket;
import com.c6906.vdam.das.config.redis.RedisUtils;
import com.c6906.vdam.das.dao.VehiclesDAO;
import com.c6906.vdam.das.model.dto.FunctionalAreaDTO;
import com.c6906.vdam.das.model.entity.*;
import com.c6906.vdam.das.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumer;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 禁区消费者运行器
 */
@Order(1)
@Component
public class FenceConsumerRunner implements CommandLineRunner {
    public static final Logger logger = LoggerFactory.getLogger(FenceConsumerRunner.class);
    public static final ObjectMapper objectMapper = new ObjectMapper();
    public static final String UNFIX_DETAIL_PRE = "UnfixDetail:";
    public static final List<String> VEHICLES_INCLUDE_PROP = new ArrayList<>(Arrays.asList("1", "2", "3", "5", "7", "12"));
    public static final List<String> VEHICLES_INCLUDE_STATUS = new ArrayList<>(Arrays.asList("1401", "1402", "1403", "1404", "1410"));
    private static final String PRE_REDIS_KEY = "SN";
    private static final String FENCE_ALARM_PRE = "AreaAlarm:";
    @Resource
    RedisUtils redisUtils;
    @Resource
    Rocket rocket;
    @Resource
    AreaCheckService areaCheckService;
    @Resource
    VehiclesDAO vehiclesDAO;
    @Resource
    EWVehiclesWarnService ewVehiclesWarnService;
    @Resource
    EWVehiclesWarnDetailService ewVehiclesWarnDetailService;
    @Resource
    AlarmService alarmService;
    @Resource
    VehicleStatusService vehicleStatusService;

    @Override
    public void run(String... args) {
        logger.info("禁区判断-消费线程池启动......");
        int poolSize = rocket.getPoolSize();
        ExecutorService executor = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < poolSize; i++) {
            logger.info("禁区判断-消费线程:{}启动...", i);
            executor.submit(() -> {
                do {
                    SimpleConsumer consumer = null;
                    try {
                        final ClientServiceProvider provider = ClientServiceProvider.loadService();
                        String endpoints = rocket.getEndpoints();
                        ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder().setEndpoints(endpoints).build();
                        String tag = "0200";
                        FilterExpression filterExpression = new FilterExpression(tag, FilterExpressionType.TAG);
                        String consumerGroup = rocket.getFenceConsumerGroup();
                        Duration awaitDuration = Duration.ofSeconds(30);
                        String topic = rocket.getVehicleTopic();
                        consumer = provider.newSimpleConsumerBuilder().setClientConfiguration(clientConfiguration).setConsumerGroup(consumerGroup).setAwaitDuration(awaitDuration).setSubscriptionExpressions(Collections.singletonMap(topic, filterExpression)).build();
                        // 每次获取消息条数
                        int maxMessageNum = rocket.getBatchSize();
                        // 设置消息接收后的不可见持续时间
                        Duration invisibleDuration = Duration.ofSeconds(1000);
                        do {
                            final List<MessageView> messages = consumer.receive(maxMessageNum, invisibleDuration);
//                            logger.info("本次消费获取消息{}条", messages.size());
                            if (!messages.isEmpty()) {
                                for (MessageView message : messages) {
                                    try {
                                        String base64String = objectMapper.writeValueAsString(message.getBody());
                                        // 消息Body转byte数组
                                        byte[] decodeBytes = Base64.decodeBase64(base64String);
                                        String msgString = new String(decodeBytes);
                                        TerminalData terminalData = JSON.parseObject(msgString, TerminalData.class);
                                        // 根据设备编号判断redis是否存在
                                        TerminalBusinessInfo terminalBusinessInfo = redisUtils.terminalInfoIsExistFormRedis(PRE_REDIS_KEY + terminalData.getTerminalSn());
                                        if (null != terminalBusinessInfo && !ObjectUtils.isEmpty(terminalBusinessInfo.getTerminalSn())) {
                                            // 排除四类不监管车辆
                                            if (!ObjectUtils.isEmpty(terminalBusinessInfo.getVehPropId()) && CollectionUtil.contains(VEHICLES_INCLUDE_PROP, terminalBusinessInfo.getVehPropId())
                                                    && !ObjectUtils.isEmpty(terminalBusinessInfo.getVehStatusId()) && CollectionUtil.contains(VEHICLES_INCLUDE_STATUS, terminalBusinessInfo.getVehStatusId())
                                                    && !ObjectUtils.isEmpty(terminalBusinessInfo.getIsNeedTerminal()) && terminalBusinessInfo.getIsNeedTerminal().equals("1")) {
                                                // 车辆定位状态分析
//                                                try {
//                                                    isFixData(terminalData, terminalBusinessInfo);
//                                                } catch (Exception e) {
//                                                    logger.error("车辆定位状态分析异常", e);
//                                                }
                                                if (terminalData.getIsFixed().equals("1")) {
                                                    try {
                                                        vehicleStatusService.onVehicleStatusReport(terminalBusinessInfo.getVehiclesCode(), terminalData.getTerminalAccStatus(), terminalData);
                                                    } catch (Exception e) {
                                                        logger.error("车辆状态更新异常", e);
                                                    }
                                                    // 定位数据，电子围栏判断
                                                    try {
                                                        isInFence(terminalData, terminalBusinessInfo);
                                                    } catch (Exception e) {
                                                        logger.error("禁区判断异常", e);
                                                    }
                                                }
                                            }
                                        } else {
                                            logger.debug("设备未初始化,数据丢弃...消息主体为={}", JSON.toJSONString(terminalData));
                                        }
                                        consumer.ack(message);
                                    } catch (Exception e) {
                                        logger.error("禁区判断-消息消费失败:messageId={}", message.getMessageId(), e);
                                    }
                                }
                            }
                        } while (true);
                    } catch (Exception e) {
                        logger.error("禁区判断-数据消费异常", e);
                    } finally {
                        if (null != consumer) {
                            consumer.close();
                            logger.info("禁区判断-数据Consumer关闭");
                        } else {
                            logger.info("禁区判断-未创建Consumer，无需关闭");
                        }
                    }
                } while (true);
            });
        }
        logger.info("禁区判断-消费线程池启动结束......");
    }

    // 判断是否在电子禁区中
    private void isInFence(TerminalData terminalData, TerminalBusinessInfo terminalBusinessInfo) {
        // 当天有申请、任务的车直接跳过分析
        if (alarmService.ifVehWithTask(terminalBusinessInfo.getVehiclesCode(), DateUtil.date().toDateStr() + '%')) {
            return;
        }
        List<FunctionalAreaDTO> fenceList = redisUtils.getFunctionalAreas();
        List<Long> whiteList = areaCheckService.getAreaWhiteListByVehiclesCode(terminalBusinessInfo.getVehiclesCode());
        // 存在禁区配置则处理,不存在则不做禁区判断
        if (null != fenceList && !fenceList.isEmpty()) {
            // 获取当前车辆是否有预警信息在redis中
            String alarm = (String) redisUtils.get(FENCE_ALARM_PRE + terminalData.getTerminalSn());
            EWVehicleDetail ewVehicleDetail = JSON.parseObject(alarm, EWVehicleDetail.class);
            // 没有预警,判断是否需要生成预警
            if (ObjectUtils.isEmpty(ewVehicleDetail)) {
                for (FunctionalAreaDTO fence : fenceList) {
                    // 白名单车辆不判断禁区 && 三个国家级景区当市的车不判断
                    if (!CollectionUtil.contains(whiteList, fence.getId())
                            && !(fence.getAreaName().equals("张家界武陵源") && terminalBusinessInfo.getRegionCode().startsWith("4308"))
                            && !(fence.getAreaName().equals("凤凰古城") && terminalBusinessInfo.getRegionCode().startsWith("4331"))
                            && !(fence.getAreaName().equals("南岳衡山") && terminalBusinessInfo.getRegionCode().startsWith("4304"))) {
                        if (areaCheckService.isPoiWithinNoParkingArea(terminalData.getLongitude(), terminalData.getLatitude(), fence.getArea(), fence.getMinArea(), fence.getMaxArea())) { // 进入禁区,创建未生效预警
                            EWVehicleDetail newEWVehicleDetail = new EWVehicleDetail(fence, terminalBusinessInfo);
                            newEWVehicleDetail.setFirstInAreaTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                            // acc为0或速度为0
                            if (terminalData.getTerminalAccStatus().equals("0") || terminalData.getSpeed().equals("0.0")) {
                                newEWVehicleDetail.setFirstParkAreaTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                            }
                            newEWVehicleDetail.setStartTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                            newEWVehicleDetail.setStartMileage(NumberUtil.parseDouble(terminalData.getTerminalMiles()));
                            newEWVehicleDetail.setStartLocLat(NumberUtil.parseDouble(terminalData.getLatitude()));
                            newEWVehicleDetail.setStartLocLng(NumberUtil.parseDouble(terminalData.getLongitude()));
                            redisUtils.set(FENCE_ALARM_PRE + terminalData.getTerminalSn(), JSON.toJSONString(newEWVehicleDetail));
                            break;
                        }
                    }
                }
            } else if (ewVehicleDetail.getStatusFlag() == 0) { // 有未生效预警,判断是否需要生效或清理
                FunctionalAreaDTO functionalArea = fenceList.stream().filter(fence -> fence.getId().equals(ewVehicleDetail.getFenceId())).findFirst().orElse(null);
                if (null != functionalArea) {
                    // 在禁区内,判断是否满足预警生效条件
                    if (areaCheckService.isPoiWithinNoParkingArea(terminalData.getLongitude(), terminalData.getLatitude(), functionalArea.getArea(), functionalArea.getMinArea(), functionalArea.getMaxArea())) {
                        /*
                        // 停车状态
                        if (terminalData.getTerminalAccStatus().equals("0") || terminalData.getSpeed().equals("0.0")) {
                            if (ewVehicleDetail.getFirstParkAreaTime() != null) {
                                long duration = DateUtil.parseDateTime(terminalData.getTerminalTime()).getTime() - ewVehicleDetail.getFirstParkAreaTime().getTime();
                                long durationMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
                                if (durationMinutes >= functionalArea.getEnterStopTime().longValue()) {
                                    ewVehicleDetail.setStatusFlag(1);
                                    ewVehicleDetail.setCreateTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
                                    // 数据库插入预警记录
                                    ewVehicleDetailDAO.insert(ewVehicleDetail);
                                }
                            } else {
                                ewVehicleDetail.setFirstParkAreaTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                            }
                        } else { // 行驶状态
                            // 已经有第一次驶入时间,判断是否满足时间条件
                            if (ewVehicleDetail.getFirstInAreaTime() != null) {
                                long duration = DateUtil.parseDateTime(terminalData.getTerminalTime()).getTime() - ewVehicleDetail.getFirstInAreaTime().getTime();
                                long durationMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
                                if (durationMinutes >= functionalArea.getEnterStayTime().longValue()) {
                                    ewVehicleDetail.setStatusFlag(1);
                                    ewVehicleDetail.setCreateTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
                                    // 数据库插入预警记录
                                    ewVehicleDetailDAO.insert(ewVehicleDetail);
                                }
                            } else { // 没有第一次驶入时间,设置第一次驶入时间
                                ewVehicleDetail.setFirstInAreaTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                            }
                        }
                         */
                        if (ewVehicleDetail.getFirstInAreaTime() != null) {
                            long duration = DateUtil.between(ewVehicleDetail.getFirstInAreaTime(), DateUtil.parseDateTime(terminalData.getTerminalTime()), DateUnit.MINUTE);
                            if (duration > functionalArea.getEnterStayTime() || duration > functionalArea.getEnterStopTime()) {
                                ewVehicleDetail.setStatusFlag(1);
                                ewVehicleDetail.setCreateTime(DateUtil.date());
                                // 数据库插入预警记录
//                                EWVehiclesWarn ewVehiclesWarn = new EWVehiclesWarn(ewVehicleDetail);
//                                VehiclesTask vehiclesTask = vehiclesDAO.selectRuningTaskByPlate(terminalData.getVehiclesCode());
//                                if (null != vehiclesTask) {
//                                    ewVehiclesWarn.setObjectCode(vehiclesTask.getUseCode());
//                                }
//                                ewVehicleDetail.setEwRemark(ewVehiclesWarn.getEwRemark());
//                                EWVehiclesWarnDetail ewVehiclesWarnDetail = new EWVehiclesWarnDetail(ewVehicleDetail, ewVehiclesWarn, terminalBusinessInfo);
//                                ewVehiclesWarnService.save(ewVehiclesWarn);
//                                ewVehiclesWarnDetailService.save(ewVehiclesWarnDetail);
//                                ewVehicleDetailDAO.insert(ewVehicleDetail);
                            }
                        } else {
                            ewVehicleDetail.setFirstInAreaTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                        }
                        redisUtils.set(FENCE_ALARM_PRE + terminalData.getTerminalSn(), JSON.toJSONString(ewVehicleDetail));
                    } else { // 预警未生效,车辆已出禁区,则清理预警信息
                        redisUtils.delete(FENCE_ALARM_PRE + terminalData.getTerminalSn());
                    }
                }
            } else if (ewVehicleDetail.getStatusFlag() == 1) { // 有已生效未结束预警,判断是否需要结束
                FunctionalAreaDTO functionalArea = fenceList.stream().filter(fence -> fence.getId().equals(ewVehicleDetail.getFenceId())).findFirst().orElse(null);
                if (null != functionalArea) {
                    // 出围栏则判断是否满足时间条件
                    if (!areaCheckService.isPoiWithinNoParkingArea(terminalData.getLongitude(), terminalData.getLatitude(), functionalArea.getArea(), functionalArea.getMinArea(), functionalArea.getMaxArea())) {
                        /*
                        // 停车状态
                        if (terminalData.getTerminalAccStatus().equals("0") || terminalData.getSpeed().equals("0.0")) {
                            if (ewVehicleDetail.getFirstParkOutAreaTime() == null) {
                                ewVehicleDetail.setFirstParkOutAreaTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                                if (ewVehicleDetail.getEndTime() == null) {
                                    ewVehicleDetail.setEndLocLng(NumberUtil.parseDouble(terminalData.getLongitude()));
                                    ewVehicleDetail.setEndLocLat(NumberUtil.parseDouble(terminalData.getLatitude()));
                                    ewVehicleDetail.setEndTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                                    ewVehicleDetail.setEndMileage(NumberUtil.parseDouble(terminalData.getTerminalMiles()));
                                    ewVehicleDetail.setMileage(ewVehicleDetail.getEndMileage() - ewVehicleDetail.getStartMileage());
                                    ewVehicleDetail.setDuration((int) TimeUnit.MILLISECONDS.toMinutes(ewVehicleDetail.getEndTime().getTime() - ewVehicleDetail.getStartTime().getTime()));
                                }
                                redisUtils.set(FENCE_ALARM_PRE + terminalData.getTerminalSn(), JSON.toJSONString(ewVehicleDetail));
                            } else {
                                long duration = DateUtil.parseDateTime(terminalData.getTerminalTime()).getTime() - ewVehicleDetail.getFirstParkOutAreaTime().getTime();
                                long durationMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
                                if (durationMinutes >= functionalArea.getLeaveStopTime().longValue()) {
                                    ewVehicleDetail.setUpdateTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
                                    // 数据库更新预警记录
                                    ewVehicleDetailDAO.updateById(ewVehicleDetail);
                                    // 更新完数据库清楚redis中告警信息
                                    redisUtils.del(FENCE_ALARM_PRE + terminalData.getTerminalSn());
                                }
                            }
                        } else { // 行驶状态
                            if (ewVehicleDetail.getFirstOutAreaTime() == null) {
                                ewVehicleDetail.setFirstOutAreaTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                                if (ewVehicleDetail.getEndTime() == null) {
                                    ewVehicleDetail.setEndLocLng(NumberUtil.parseDouble(terminalData.getLongitude()));
                                    ewVehicleDetail.setEndLocLat(NumberUtil.parseDouble(terminalData.getLatitude()));
                                    ewVehicleDetail.setEndTime(DateUtil.parseDateTime(terminalData.getTerminalTime()));
                                    ewVehicleDetail.setEndMileage(NumberUtil.parseDouble(terminalData.getTerminalMiles()));
                                    ewVehicleDetail.setMileage(ewVehicleDetail.getEndMileage() - ewVehicleDetail.getStartMileage());
                                    ewVehicleDetail.setDuration((int) TimeUnit.MILLISECONDS.toMinutes(ewVehicleDetail.getEndTime().getTime() - ewVehicleDetail.getStartTime().getTime()));
                                }
                                redisUtils.set(FENCE_ALARM_PRE + terminalData.getTerminalSn(), JSON.toJSONString(ewVehicleDetail));
                            } else {
                                long duration = DateUtil.parseDateTime(terminalData.getTerminalTime()).getTime() - ewVehicleDetail.getFirstOutAreaTime().getTime();
                                long durationMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
                                if (durationMinutes >= functionalArea.getLeaveStayTime().longValue()) {
                                    ewVehicleDetail.setUpdateTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
                                    // 数据库更新预警记录
                                    ewVehicleDetailDAO.updateById(ewVehicleDetail);
                                    // 更新完数据库清楚redis中告警信息
                                    redisUtils.del(FENCE_ALARM_PRE + terminalData.getTerminalSn());
                                }
                            }
                        }
                         */
                        if (ewVehicleDetail.getFirstOutAreaTime() == null) {
                            Date terminalTime = DateUtil.parseDateTime(terminalData.getTerminalTime());
                            ewVehicleDetail.setFirstOutAreaTime(terminalTime);
                            if (ewVehicleDetail.getEndTime() == null) {
                                ewVehicleDetail.setEndLocLng(NumberUtil.parseDouble(terminalData.getLongitude()));
                                ewVehicleDetail.setEndLocLat(NumberUtil.parseDouble(terminalData.getLatitude()));
                                ewVehicleDetail.setEndTime(terminalTime);
                                ewVehicleDetail.setEndMileage(NumberUtil.parseDouble(terminalData.getTerminalMiles()));
                                ewVehicleDetail.setMileage(NumberUtil.sub(ewVehicleDetail.getEndMileage(), ewVehicleDetail.getStartMileage()));
                                ewVehicleDetail.setDuration(DateUtil.between(ewVehicleDetail.getEndTime(), ewVehicleDetail.getStartTime(), DateUnit.MINUTE));
                            }
                            redisUtils.set(FENCE_ALARM_PRE + terminalData.getTerminalSn(), JSON.toJSONString(ewVehicleDetail));
                        } else {
                            long duration = DateUtil.between(ewVehicleDetail.getFirstOutAreaTime(), DateUtil.parseDateTime(terminalData.getTerminalTime()), DateUnit.MINUTE);
                            double mileage = NumberUtil.sub(ewVehicleDetail.getEndMileage(), ewVehicleDetail.getStartMileage());
                            if (duration >= functionalArea.getLeaveStayTime() || mileage >= functionalArea.getLeaveStopTime()) {
                                ewVehicleDetail.setUpdateTime(DateUtil.date());
                                // 数据库插入预警记录
                                EWVehiclesWarn ewVehiclesWarn = new EWVehiclesWarn(ewVehicleDetail, terminalBusinessInfo);
                                VehiclesTask vehiclesTask = vehiclesDAO.selectRuningTaskByPlate(terminalData.getVehiclesCode());
                                if (null != vehiclesTask) {
                                    ewVehiclesWarn.setObjectCode(vehiclesTask.getUseCode());
                                }
                                ewVehicleDetail.setEwRemark(ewVehiclesWarn.getEwRemark());
                                EWVehiclesWarnDetail ewVehiclesWarnDetail = new EWVehiclesWarnDetail(ewVehicleDetail, ewVehiclesWarn, terminalBusinessInfo);
                                ewVehiclesWarnService.save(ewVehiclesWarn);
                                ewVehiclesWarnDetailService.save(ewVehiclesWarnDetail);
                                // 数据库更新预警记录
//                                ewVehicleDetailDAO.updateById(ewVehicleDetail);
                                // 更新完数据库清除redis中告警信息
                                redisUtils.delete(FENCE_ALARM_PRE + terminalData.getTerminalSn());
                            }
                        }
                    } else { // 还在围栏中,清空出围栏时间
                        ewVehicleDetail.setFirstOutAreaTime(null);
                        ewVehicleDetail.setFirstParkOutAreaTime(null);
                        ewVehicleDetail.setEndLocLng(null);
                        ewVehicleDetail.setEndLocLat(null);
                        ewVehicleDetail.setEndMileage(null);
                        ewVehicleDetail.setEndTime(null);
                        ewVehicleDetail.setMileage(null);
                        ewVehicleDetail.setDuration(null);
                        redisUtils.set(FENCE_ALARM_PRE + terminalData.getTerminalSn(), JSON.toJSONString(ewVehicleDetail));
                    }
                }
            } else {
                ewVehicleDetail.setStatusFlag(0);
                redisUtils.set(FENCE_ALARM_PRE + terminalData.getTerminalSn(), JSON.toJSONString(ewVehicleDetail));
            }
        }
    }

    // 判断是否未定位
    private void isFixData(TerminalData terminalData, TerminalBusinessInfo terminalBusinessInfo) {
        // 未定位，判断是否需要生成未定位预警
        // 已定位，判断是否需要关闭预警
        VehiclesUnfixDetail vehiclesUnfixDetail = redisUtils.getVehiclesUnfixDetail(terminalData.getTerminalSn());
        if (vehiclesUnfixDetail != null) {
            if (terminalData.getIsFixed().equals("1")) {
                vehiclesUnfixDetail.setEndTime(DateUtil.parse(terminalData.getTerminalTime()));
                vehiclesUnfixDetail.setEndLon(NumberUtil.add(terminalData.getLongitude()));
                vehiclesUnfixDetail.setEndLat(NumberUtil.add(terminalData.getLatitude()));
                vehiclesUnfixDetail.setDuration(DateUtil.between(vehiclesUnfixDetail.getStartTime(), vehiclesUnfixDetail.getEndTime(), DateUnit.MINUTE));
                vehiclesUnfixDetail.setUpdateTime(DateUtil.date());
                redisUtils.delete(UNFIX_DETAIL_PRE + terminalData.getTerminalSn());
                if (vehiclesUnfixDetail.getDuration() < 12 * 60) {
                    vehiclesDAO.deleteVehiclesUnfixDetail(vehiclesUnfixDetail);
                } else {
                    vehiclesDAO.updateVehiclesUnfixDetail(vehiclesUnfixDetail);
                }
            }
        } else { // 无预警判断是否需要生成
            if (terminalData.getIsFixed().equals("0")) {
                VehiclesUnfixDetail newVUDetail = new VehiclesUnfixDetail(terminalData, terminalBusinessInfo);
                redisUtils.set(UNFIX_DETAIL_PRE + terminalData.getTerminalSn(), JSON.toJSONString(newVUDetail));
                vehiclesDAO.insertVehiclesUnfixDetail(newVUDetail);
            }
        }
    }
}
